package com.liuguang.gateway.config.security.impl;


import com.liuguang.gateway.config.security.dao.MenuDOMapper;
import com.liuguang.gateway.config.security.dao.UserDOMapper;
import com.liuguang.api.gateway.security.pojo.RoleDO;
import com.liuguang.api.gateway.security.pojo.bo.AuthUser;
import com.liuguang.gateway.config.security.others.CurrentUserHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Description：
 * @Author: wanghr
 * Date: 10:30 AM 2020/9/17
 * Version: 1.0
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private UserDOMapper userDoMapper;

    @Autowired
    private MenuDOMapper menuDOMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        List<AuthUser> authUserList = userDoMapper.selectByUsername(username);
        int authUserListSize = authUserList.size();
        if (authUserListSize != 1) {
            logger.info("根据用户名查询不到用户，或查询出多个用户");
            return null;
        }
        // todo: 角色的列表应该使用set， 但是关系到 hashcode 暂时搁置
        AuthUser authUser = authUserList.get(0);
        List<RoleDO> roleList = authUser.getRoleList();
        //每个人只能有一个角色
//        List<MenuDO> menuDOList = menuDOMapper.selectByRoleList(roleList);

        //此时将用户信息保存到 UserContextHodler中，虽然此时没有验证，用户是否能登录成功，都不影响，
        // 成功了，直接去验证登录ip是否是常用的ip
        // 不成功，线程直接结束，伴随这用户信息也消失了
        CurrentUserHolder.setCurrentUser(authUser);

        StringBuilder temp = new StringBuilder();
        roleList.forEach(roleDO -> temp.append(roleDO.getRoleName()+","));
//        menuDOList.forEach(menuDO -> authorities.append(menuDO.getId()+":"+menuDO.getMenuName()));
        logger.info("{},角色列表:{}",username,temp);
//

        List<GrantedAuthority> authorities = new ArrayList<>();
        roleList.forEach(roleDO -> authorities.add(new SimpleGrantedAuthority(roleDO.getRoleName())));
        return new User(username, authUser.getPassword(), authorities);
    }
}
